package cn.senwill.service.impl;

import cn.senwill.domain.Result;
import cn.senwill.domain.entity.Account;
import cn.senwill.mapper.AccountMapper;
import cn.senwill.service.AccountService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class AccountServiceImpl implements AccountService {

    private AccountMapper accountMapper;

    @Autowired
    public void setAccountMapper(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    @Override
    public Result update(JSONObject jsonObject) {
//        try {
            Long userId = Long.parseLong(String.valueOf(jsonObject.get("user_id")));
            BigDecimal used = new BigDecimal(String.valueOf(jsonObject.get("used")));
            System.out.println(":::: -> " + jsonObject.toJSONString());
            Account account = accountMapper.selectById(userId);
            if (account != null) {
                Account newAccount = new Account();
                newAccount.setId(account.getId());
                newAccount.setUserId(userId);
                newAccount.setTotal(account.getTotal());
                newAccount.setUsed(account.getUsed().add(used));
                newAccount.setResidue(account.getResidue().subtract(used));
                System.out.println(":::: -> " + newAccount.toString());
//                int n = 1/0;
                accountMapper.updateById(newAccount);
                return Result.success("操作成功 ~", newAccount);
            } else {
                return Result.error("操作失败 -> 该用户账户为空");
            }
//        } catch (Exception e) {
//            return Result.error("操作失败 -> " + e.getMessage());
//        }
    }
}
